package com.example.springsecurityextraloginfield.service.impl;

import com.example.springsecurityextraloginfield.entity.UserDAO;
import com.example.springsecurityextraloginfield.repository.UserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class SimpleUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String[] usernameAndDomain = StringUtils.split(username,String.valueOf(Character.LINE_SEPARATOR));
        if (usernameAndDomain == null || usernameAndDomain.length != 2) {
            throw new UsernameNotFoundException("用户名和域名必须提供");
        }
        UserDAO userDAO = userRepository.findUser(usernameAndDomain[0],usernameAndDomain[1]);
        if (userDAO == null) {
            throw new UsernameNotFoundException("Username not found for domain,username=" + usernameAndDomain[0] + ",domain=" + usernameAndDomain[1]);
        }
        return userDAO;
    }
}
